package com.agilespirit.presentation.components.application.list;

import java.util.List;

import org.apache.wicket.markup.html.basic.Label;
import org.apache.wicket.markup.html.link.BookmarkablePageLink;
import org.apache.wicket.markup.html.link.Link;
import org.apache.wicket.markup.html.list.ListItem;
import org.apache.wicket.markup.html.list.ListView;
import org.apache.wicket.markup.html.panel.Panel;
import org.apache.wicket.model.IModel;
import org.apache.wicket.model.LoadableDetachableModel;
import org.apache.wicket.model.Model;
import org.apache.wicket.request.mapper.parameter.PageParameters;

import com.agilespirit.application.ApplicationServiceImpl;
import com.agilespirit.domain.Application;
import com.agilespirit.presentation.pages.application.wizard.ApplicationWizardPage;

public class ApplicationList extends Panel {

  private static final long serialVersionUID = 4907116541209734919L;

  /* Components */
  ListView<Application> list;

  public ApplicationList(String id) {
    super(id);
    buildList();
  }

  private void buildList() {
    IModel<List<Application>> listModel = new LoadableDetachableModel<List<Application>>() {

      private static final long serialVersionUID = -1767742978019334027L;

      @Override
      protected List<Application> load() {
        return ApplicationServiceImpl.getInstance().find(null);
      }
    };

    list = new ListView<Application>("list", listModel) {

      private static final long serialVersionUID = 2317275167796337315L;

      @Override
      protected void populateItem(final ListItem<Application> item) {
        final Application application = item.getModelObject();
        item.add(new Label("id", application.getId().toString()));
        item.add(new Label("name", application.getName()));
        item.add(new Label("environment", application.getEnvironment().name()));
        item.add(new Label("platform", application.getPlatform().name()));
        item.add(new Label("country", application.getCountry().name()));
        item.add(new Label("host", application.getHost()));
        item.add(new Label("port", application.getPort().toString()));
        item.add(new Label("username", application.getUsername()));

        final PageParameters params = new PageParameters();
        params.add("application", application.getId());
        item.add(new BookmarkablePageLink<ApplicationWizardPage>("edit", ApplicationWizardPage.class, params));
        item.add(new Link<Integer>("delete", new Model<Integer>(application.getId())) {
          @Override
          public void onClick() {
            ApplicationServiceImpl.getInstance().delete(getModelObject());
          }
        });
      }
    };
    add(list);
  }

}
